<template>
  <el-container style="height: 100vh">
    <Aside/>
    <el-container style="flex-direction: column;">
      <el-main style="flex: 1; display: flex; flex-direction: column; background: linear-gradient(to right, #e0c3fc, #8ec5fc)">
        <h1 class="title">Graph Generation</h1>
        <br>
        <div class="top-container" style="border-radius: 15px; background: linear-gradient(to right, #8ec5fc, #e0c3fc)">
          <input type="file" style="margin-right: 100px; margin-top: 20px; margin-left: 40px" @change="handleFileUpload" />
          <br>
          <br>
          <div style="font-size: 15px; display: inline-block;">Table Name:</div>
          <el-input v-model="inputTN" style="width: 20%; display: inline-block;" placeholder="请输入图表名称"></el-input>
          <br>
          <br>
          <el-button plain style="margin-bottom: 10px" @click="processFile">生成图谱</el-button>
        </div>
        <div class="bottom-container" style="border-radius: 15px">
          <div id="main" style="width: 100%; height: 1000px; margin-top: 10px;"></div>
          <div class="content" style="background: whitesmoke">
            <h1>Ai 分析</h1>
            <br>
            <el-button plain @click="aiAnalyze">点击此按钮进行分析</el-button>
            <div class="content" >
              <div v-html="aiComment"></div>
            </div>
          </div>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup>
import { ref } from 'vue';
import Aside from '@/components/aside.vue';
import * as XLSX from 'xlsx';
import * as echarts from 'echarts';
import {createComment, createTable} from "@/api/user.js";
import { ElNotification } from "element-plus";

const inputTN = ref('');
const file = ref(null);
let jsonData = [];
const userId = ref('')
let tableId = ref('')
let aiComment = ref('')

async function aiAnalyze() {
  if (!tableId) {
    ElNotification({
      title: '错误',
      message: '请先创建图谱',
      type: 'error'
    });
    return;
  }

  try {
    const response = await createComment({ TableId: tableId });
    if (response.code === 200) {
      aiComment.value = response.comment; // 更新 aiComment 的值
      ElNotification({
        title: '成功',
        message: 'AI分析成功',
        type: 'success'
      });
    } else {
      ElNotification({
        title: '失败',
        message: `AI分析失败: ${response.msg}`,
        type: 'error'
      });
    }
  } catch (err) {
    ElNotification({
      title: '失败',
      message: `AI分析失败: ${err.message}`,
      type: 'error'
    });
    console.error('分析失败', err);
  }
}


function handleFileUpload(event) {
  file.value = event.target.files[0];
}

async function processFile() {
  if (inputTN.value === '') {
    ElNotification({
      title: '错误',
      message: '请输入表格名字',
      type: 'error',
    });
    return;
  }

  if (!file.value) {
    ElNotification({
      title: '错误',
      message: '请上传文件',
      type: 'error',
    });
    return;
  }

  const reader = new FileReader();

  reader.onload = async function (e) {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: 'array' });
    const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
    jsonData = XLSX.utils.sheet_to_json(firstSheet, { header: 1 });

    const nodesMap = new Map();
    const links = [];

    jsonData.slice(1).forEach((row) => {
      const node1 = row[0] ? row[0].trim() : '';
      const node2 = row[2] ? row[2].trim() : '';
      const relationship = row[1] ? row[1].trim() : '';

      if (!node1 && !node2 && !relationship) {
        return;
      }

      if (!nodesMap.has(node1)) {
        nodesMap.set(node1, { name: node1, id: nodesMap.size });
      }
      if (!nodesMap.has(node2)) {
        nodesMap.set(node2, { name: node2, id: nodesMap.size });
      }

      links.push({
        source: nodesMap.get(node1).id,
        target: nodesMap.get(node2).id,
        name: relationship,
      });
    });

    const nodes = Array.from(nodesMap.values());

    try {
      const storedUser = localStorage.getItem('user');
      if (storedUser) {
        const parsedUser = JSON.parse(storedUser);
        if (parsedUser && parsedUser.id) {
          userId.value = parsedUser.id;
          const tableData = {
            Name: inputTN.value,
            UserId: userId.value,
            TableData: JSON.stringify(jsonData.slice(1).map(row => ({
              node1: row[0],
              relationship: row[1],
              node2: row[2],
            }))),
          };

          const response = await createTable(tableData);
          // console.log(response.code)
          if (response.code === 200) {
            tableId = response.data.Id
            // console.log(tableId)
            ElNotification({
              title: '成功',
              message: '图谱创建成功',
              type: 'success',
            });
          } else {
            ElNotification({
              title: '图谱创建失败',
              message: `图谱创建失败: ${response.data.msg}`,
              type: 'error',
            });
          }
        }
      }
    } catch (err) {
      ElNotification({
        title: '图谱创建失败',
        message: '处理文件时出现错误，请稍后重试',
        type: 'error',
      });
      console.error('图谱创建失败', err);
    }

    drawChart(nodes, links);
  };

  reader.readAsArrayBuffer(file.value);
}

function drawChart(nodes, links) {
  const chartDom = document.getElementById('main');
  const myChart = echarts.init(chartDom, 'dark');

  const option = {
    title: {
      text: 'VC-kd',
      subtext: 'Node-Relationship-Node',
      top: 'bottom',
      left: 'right',
    },
    tooltip: {
      formatter: function (params) {
        if (params.dataType === 'edge') {
          return `Relationship: ${params.data.name}`;
        }
        return params.data.name;
      },
    },
    legend: [
      {
        data: [],
      },
    ],
    animationDuration: 1500,
    animationEasingUpdate: 'quinticInOut',
    series: [
      {
        name: 'Graph',
        type: 'graph',
        layout: 'force',
        data: nodes,
        links: links,
        roam: true,
        label: {
          position: 'right',
          formatter: '{b}',
        },
        lineStyle: {
          color: 'source',
          curveness: 0.3,
        },
        emphasis: {
          focus: 'adjacency',
          lineStyle: {
            width: 10,
          },
        },
        force: {
          repulsion: 1000,
        },
      },
    ],
  };

  myChart.setOption(option);
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Pacifico&display=swap');

html,
body {
  height: 100%;
  margin: 0;
}

.el-main {
  background-color: #e9eef3;
  color: #333;
  text-align: center;
}

.el-container {
  height: 100%;
}

.top-container {
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  flex: 0.4;
  justify-content: center;
  align-items: center;
}

.content {
  font-size: 18px;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.19);
  margin-top: 20px;
  width: 96%;
  font-family: Arial, sans-serif;
  background: linear-gradient(to right, #8ec5fc, #e0c3fc);
  /* 确保文本和内容靠右 */
  text-align: left;
}

.bottom-container {
  background-color: #ffffff;
  flex: 3;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 30px;
  text-align: center;
  font-family: 'Pacifico', cursive;
}
</style>
